/**
 * Session Actions Component
 * 
 * Provides actions for sessions (rename, archive, export, delete)
 */

import { Edit2, Archive, Download, Trash2, MoreVertical } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
import type { Session } from '@/types';

export interface SessionActionsProps {
  session: Session;
  onRename?: (sessionId: string, newTitle: string) => void;
  onArchive?: (sessionId: string) => void;
  onExport?: (session: Session) => void;
  onDelete?: (sessionId: string) => void;
}

export function SessionActions({
  session,
  onRename,
  onArchive,
  onExport,
  onDelete,
}: SessionActionsProps) {
  const handleRename = () => {
    const newTitle = prompt('重命名会话：', session.title || '新对话');
    if (newTitle && newTitle !== session.title) {
      onRename?.(session.id, newTitle);
    }
  };

  const handleArchive = () => {
    if (confirm(`确定要归档会话"${session.title}"吗？`)) {
      onArchive?.(session.id);
    }
  };

  const handleExport = () => {
    onExport?.(session);
  };

  const handleDelete = () => {
    if (confirm(`确定要删除会话"${session.title}"吗？此操作不可恢复。`)) {
      onDelete?.(session.id);
    }
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          className="h-7 w-7"
          title="会话操作"
          onClick={(e) => e.stopPropagation()}
        >
          <MoreVertical className="w-4 h-4" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-48">
        {onRename && (
          <DropdownMenuItem onClick={handleRename}>
            <Edit2 className="w-4 h-4 mr-2" />
            <span>重命名</span>
          </DropdownMenuItem>
        )}

        {onArchive && (
          <DropdownMenuItem onClick={handleArchive}>
            <Archive className="w-4 h-4 mr-2" />
            <span>归档</span>
          </DropdownMenuItem>
        )}

        {onExport && (
          <DropdownMenuItem onClick={handleExport}>
            <Download className="w-4 h-4 mr-2" />
            <span>导出</span>
          </DropdownMenuItem>
        )}

        {onDelete && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onClick={handleDelete}
              className="text-red-600 focus:text-red-600 focus:bg-red-50"
            >
              <Trash2 className="w-4 h-4 mr-2" />
              <span>删除</span>
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

/**
 * Export session to different formats
 */
export function exportSession(session: Session, format: 'json' | 'markdown' | 'text' = 'json') {
  let content: string;
  let filename: string;
  let mimeType: string;

  const title = session.title || '新对话';
  const timestamp = new Date(session.updatedAt).toISOString().split('T')[0];

  switch (format) {
    case 'markdown':
      content = generateMarkdown(session);
      filename = `${title}-${timestamp}.md`;
      mimeType = 'text/markdown';
      break;

    case 'text':
      content = generateText(session);
      filename = `${title}-${timestamp}.txt`;
      mimeType = 'text/plain';
      break;

    case 'json':
    default:
      content = JSON.stringify(session, null, 2);
      filename = `${title}-${timestamp}.json`;
      mimeType = 'application/json';
      break;
  }

  // 创建下载链接
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function generateMarkdown(session: Session): string {
  const title = session.title || '新对话';
  const date = new Date(session.createdAt).toLocaleString('zh-CN');
  
  let markdown = `# ${title}\n\n`;
  markdown += `**创建时间**: ${date}\n`;
  markdown += `**消息数量**: ${session.messages.length}\n\n`;
  markdown += `---\n\n`;

  session.messages.forEach((msg, index) => {
    const role = msg.role === 'user' ? '👤 用户' : '🤖 助手';
    const time = new Date(msg.timestamp).toLocaleTimeString('zh-CN');
    
    markdown += `## ${role} (${time})\n\n`;
    markdown += `${msg.content}\n\n`;
    
    if (index < session.messages.length - 1) {
      markdown += `---\n\n`;
    }
  });

  return markdown;
}

function generateText(session: Session): string {
  const title = session.title || '新对话';
  const date = new Date(session.createdAt).toLocaleString('zh-CN');
  
  let text = `${title}\n`;
  text += `${'='.repeat(title.length)}\n\n`;
  text += `创建时间: ${date}\n`;
  text += `消息数量: ${session.messages.length}\n\n`;
  text += `${'-'.repeat(50)}\n\n`;

  session.messages.forEach((msg, index) => {
    const role = msg.role === 'user' ? '用户' : '助手';
    const time = new Date(msg.timestamp).toLocaleTimeString('zh-CN');
    
    text += `[${role}] (${time})\n`;
    text += `${msg.content}\n\n`;
    
    if (index < session.messages.length - 1) {
      text += `${'-'.repeat(50)}\n\n`;
    }
  });

  return text;
}

